<script setup lang="ts">
import { reactive, ref, watch } from "vue";

const count = ref(0);
const name = ref("123");

type IPerson = { name: string; info: { address: string; phone: string } };

const person = reactive<IPerson>({
  name: "张三",
  info: {
    address: "北京昌平",
    phone: "010-12345678",
  },
});
//  侦听器单个的用法
//  watch(count, (newValue, oldValue) => {
//    console.log(newValue, oldValue)
//  })
// 监听多个的响应式数据-newValue和oldValue是数组，顺序按照传入顺序排列
//  watch([count, name], (newValue, oldValue) => {
//    console.log("新值" +newValue, "旧值" +oldValue)
//  })

// Watch监听响应式对象中属性的变化
// watch(() => person.name, (newValue, oldValue) => {
//     console.log("新值" +newValue, "旧值" +oldValue)
// })
watch(
  person,
  (newValue, oldValue) => {
    console.log("新值" + newValue, "旧值" + oldValue);
  },
  {
    deep: true, // 开启深度监听
    immediate: true, // 初始化时执行一次
  }
);
</script>

<template>
  <h1>Watch最简单用法</h1>
  <button @click="count--">-</button>
  <span>{{ count }}</span>
  <button @click="count++">+</button>
  <input type="text" v-model="name" />
  <h1>Watch监听属性的变化</h1>
  <ul>
    <li v-for="(value, key, index) in person" :key="index">
      {{ value }}
    </li>
  </ul>
  <button @click="person.name = '李四'">修改名字</button>
  <button @click="person.info.address = '深圳南山'">修改信息</button>
</template>

<style scoped></style>
